/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.dwusoft.wbd.send.impl  
 */
package com.dwusoft.sendmsg.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.dwusoft.sendmsg.common.SendToolsUtil;
import com.dwusoft.sendmsg.common.entity.Sendmsg;
import com.dwusoft.sendmsg.manager.SendService;
import com.dwusoft.sendmsg.service.template.TemplateHelper;
import com.apache.tools.StrUtil;

/**
 * description:  向邮箱发信息通知
 * @author Hou Dayu 创建时间：2016-5-6  
 * @Copyright(c)2014:北京东吴软件技术有限公司
 */
public class SendEmailServiceImpl implements SendService {

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.dwusoft.wbd.send.SendService#sendMessage(java.util.Map)  
	 */
	public boolean sendMessage(Sendmsg msg, Map<String, String> params) {
		String password = msg.getUserPass();
		String host = msg.getMailHost();
		String from = msg.getFromUserEmail();
		String protocol = msg.getMailProtocol();
		String title = msg.getMsgTitle();
		try {
			Properties props = new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			Session session = Session.getDefaultInstance(props, null);
			session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			InternetAddress fromAddress = new InternetAddress(from);
			message.setFrom(fromAddress);
			InternetAddress toAddress = new InternetAddress(msg.getToUserEmail());
			message.addRecipient(Message.RecipientType.TO, toAddress);
			message.setSubject(title);
			String body = "";
			try {
				String tempName = StrUtil.doNull(msg.getSpare1(), "sendEmail.ftl");
				params = SendToolsUtil.getInstance().toMap(msg);
				body = TemplateHelper.instance().getTemplateStr(tempName, params);
			} catch (Exception e) {
				return false;
			}
			message.setContent(body, "text/html;charset=UTF-8"); //发送HTML邮件，内容样式比较丰富  
			message.setSentDate(new Date());//设置发信时间  
			Transport transport = session.getTransport(protocol);
			transport.connect(from, password);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return false;
	}

}
